package com.liner;

import java.util.Arrays;
import java.util.Random;

/**
 * @author 一条淡水鱼 ゆ
 * @Classname sort
 * @Description 冒泡排序
 * @Date 2023-04-01
 */
public class BubbleSort {
    static Random random = new Random();
    public static void main(String[] args) {

        int[] array = getInts();
        System.out.println(Arrays.toString(array));

        sort(array);
        System.out.println(Arrays.toString(array));


    }

    public static int[] getInts() {
        //随机数大小上限
        int numberBound = 100;

        //随机数数量
        int numbersCount = 50;

        //生成随机数组成数组
        int[] array = new int[numbersCount];

        for (int i = 0; i <array.length ; i++) {

            array[i] = random.nextInt(numberBound);
        }
        return array;
    }

    private static void sort(int[] numbers) {
        //对比次数
        int compareCount = 0;
        //交换次数
        int swapCount = 0;

        //记录排序开始前的时间值
        long startTime = System.currentTimeMillis();

        for (int i = 0; i < numbers.length -1; i++) {
            boolean flag = false;
            for (int j = 0; j < numbers.length - i -1; j++) {
                compareCount++;
                if (numbers[j] > numbers[j+1]) {
                    int temp = numbers[j];
                    numbers[j] = numbers[j+1];
                    numbers[j+1] = temp;
                    flag = true;
                    swapCount++;
                }
            }
            if (!flag) {
                break;
            }
        }

        long endTime = System.currentTimeMillis();

        System.out.println("耗时:" + (endTime - startTime));
        System.out.println("对比次数:" + compareCount);
        System.out.println("交换次数:" + swapCount);
    }
}
